<?php
namespace app\index\controller;
use think\Controller;
use think\WeixinPay;
use think\Wxmessage;



class Order extends Controller{

    
    private function makeOrderNumber() {
        $order_sn = (intval(date('Y')) - 2010) . date('m') . date('d') . substr(time() , -5) . substr(microtime() , 2, 4);
        return str_pad($order_sn, 12, rand(0, 9));
    }
    
    
    /**
     * 下订单
     * @return [type] [description]
     */
    public function add()
    {
        $post = input('post.');
        if(empty($post['user_id'])){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        if(empty($post['type'])){
            $this->ajaxReturn(null, '未选择类型', 202);
        }

        $user = db('user')->find($post['user_id']);
        if(empty($user)){
            $this->ajaxReturn(null, '无此用户', 205);
        }

        if(empty($user['openid'])){
            $this->ajaxReturn(null, '参数错误', 206);
        }
        
        if(empty($post['equipment_id'])){
            $this->ajaxReturn(null, '无设备', 203);
        }

        $equipment = db('equipment')->find($post['equipment_id']);
        if(empty($equipment)){
            $this->ajaxReturn(null, '无此设备', 205);
        }

        if($post['type']==1){
            $order = db('order')->where(['user_id'=>$post['user_id'], 'type'=>1, 'status'=>1])->value('order_id');
            if($order) $this->ajaxReturn(null, '磨刀进行中', 205);
        }
        
        if($post['type']==2){
            $order = db('order')->where(['user_id'=>$post['user_id'], 'type'=>2, 'status'=>1])->value('order_id');
            if($order) $this->ajaxReturn(null, '磨刀进行中', 205);

            $order2 = db('order')->where(['user_id'=>$post['user_id'], 'type'=>2, 'status'=>2])->value('order_id');
            if($order2) $this->ajaxReturn(null, '还未取刀', 205);

        }

        $basic_price = db('config')->value('basic_price');
        $data['type']       = $post['type'];
        $data['equipment_id']       = $equipment['id'];
        $data['equipment_name']     = $equipment['name'];
        $data['equipment_address']  = $equipment['address'];
        $data['user_id']    = $user['id'];
        $data['name']       = $user['nickName'];
        $data['avatarUrl']  = $user['avatarUrl'];
        $data['order_no']   = $this->makeOrderNumber();
        $data['basic_price']= $basic_price;
        $data['makedate']   = !empty($post['makedate'])?$post['makedate']:date('Y-m-d');
        $data['status']     = 1;
        $data['ctime'] 	    = time();
        $data['cdate'] 	    = date('Y-m-d H:i:s');
        $order_id  = db('order')->insertGetId($data);
        if($order_id){
            $user_e_id = db('user')->where('id', $post['user_id'])->value('equipment_id');
            if($user_e_id != $equipment['id']){
                db('user')->where('id', $post['user_id'])->update(['equipment_id'=>$equipment['id']]);
            }
            $weixinpay = new WeixinPay($user['openid'], $data['order_no'], '磨刀', 'add', $basic_price, '');
            $return = $weixinpay->pay();
            $return['order_id'] = $order_id;
            $this->ajaxReturn($return, '下单成功', 200);
        }else{
            $this->ajaxReturn(null, '下单失败', 204);
        }
    }


    private function money($ctime)
    {
        $config = db('config')->find();
        $money = 0;
        //计算天数
        $timediff = time()-$ctime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);

        if($days==0){
            if($hours > 10){
                $money = $config['repair_10'];
            }
        }
        else if($days>0){
            $money = $config['repair_10'] + $days*$config['repair_24'];
        }

        $ret['price'] = $money;
        $ret['date'] = $days.'天'.$hours.'时'.$mins.'分';
        return $ret;
    }

    /**
     * 支付金额
     */
    public function orderprice()
    {
        $userId = input('get.user_id');
        if(empty($userId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $order = db('order')->where(['user_id'=>$userId, 'type'=>2, 'status'=>2])->field('order_id,ctime')->find();
        if(empty($order)){
            $this->ajaxReturn(null, '订单不存在', 202);
        }
        
        $money = $this->money($order['ctime']);
        $this->ajaxReturn($money, '支付金额', 200);
    }



    public function pay()
    {
        $post = input('post.');
        $userId = $post['user_id'];

        if(empty($userId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $openid = db('user')->where('id', $userId)->value('openid');
        if(empty($openid)){
            $this->ajaxReturn(null, '无此用户', 204);
        }

        $order = db('order')->where(['user_id'=>$userId, 'type'=>2, 'status'=>2])->field('order_id,order_no,user_id,status,transaction_no,basic_price,ctime')->find();
        if(empty($order)){
            $this->ajaxReturn(null, '无取刀操作', 202);
        }

        if($order['status'] == 3){
            $this->ajaxReturn(null, '已支付', 206);
        }

        if($order['status'] != 2){
            $this->ajaxReturn(null, '不在支付状态', 207);
        }
        
        $order_no = $this->makeOrderNumber();
        $money = $this->money($order['ctime']);
        if($money['price']==0){
            db('order')->where('order_id', $order['order_id'])->update(['status'=>3, 'total_price'=>$order['basic_price']]);
            $this->ajaxReturn(['order_id'=>$order['order_id']], '支付成功', 200);
        }
        
        $weixinpay = new WeixinPay($openid, $order_no, '磨刀', 'pay', $money['price'], '');
        $return = $weixinpay->pay();
        if($return['return_code'] =='FAIL'){
            $this->ajaxReturn($return, $return['return_msg'], 204);
        }
        if($return['result_code'] == 'SUCCESS'){
            db('order')->where('order_id', $order['order_id'])->update(['order_no'=>$order_no]);
            $this->ajaxReturn($return, '支付成功', 200);
        }else{
            $this->ajaxReturn($return, $return['err_code_des'], 204);
        }
    }



    /**
     * 订单详情
     * @return [type] [description]
     */
    public function orderDetails()
    {
        $userId = input('param.user_id',0);
        if(empty($userId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $order = db('order')->where(['user_id'=>$userId, 'type'=>2, 'status'=>2])->field('order_id,order_no,user_id,status,transaction_no,basic_price,ctime')->find();
        if ($order) {
            $this->ajaxReturn($order, 'ok', 200);
        }else{
            $this->ajaxReturn(null, '数据为空', 204);
        }
    }



    
    /**
     * 取消订单
     * @return [type] [description]
     */
    public function cancel()
    {
        $post = input('param.');
        $userId = $post['user_id'];

        if(empty($userId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $order = db('order')->where(['user_id'=>$userId, 'status'=>1])->field('order_id,user_id,status')->find();
        if(empty($order)){
            $this->ajaxReturn(null, '无订单可操作', 203);
        }

        $user = db('user')->field('id,openid,nickName')->find($order['user_id']);
        if(empty($user)){
            $this->ajaxReturn(null, '无此用户', 201);
        }
        
        $return = db('order')->where('order_id', $order['order_id'])->update(['status'=>-1]);
        if($return !== false){
            $this->ajaxReturn(['order_id'=>$order['order_id']], '取消成功', 200);
        }else{
            $this->ajaxReturn(null, '取消失败', 207);
        }

    }


    /**
     * 支付成功消息通知
     * @return [type] [description]
     */
    public function successPay()
    {
        $post = input('param.');
        $orderId = $post['order_id'];
        $formId = $post['form_id'];
        if(empty($orderId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $order = db('order')->where('order_id', $orderId)->field('order_id,order_no,user_id,pay_fee,status,name')->find();
        if(empty($order)){
            $this->ajaxReturn(null, '订单不存在', 203);
        }

        $user = db('user')->field('id,openid,nickName')->find($order['user_id']);
        if(empty($user)){
            $this->ajaxReturn(null, '无此用户', 201);
        }

        if($order['status'] != 2){
            $this->ajaxReturn(null, '支付状态不正确', 204);
        }

        $plist   = '';
        $prodlist = json_decode($order['json'], true);
        if($prodlist){
            foreach ($prodlist as $v) {
                $plist .= $v['product_name'].'x'.$v['num'].',';                
            }
        }

        $data = '{
                      "keyword1": {
                        "value": "'.$order['order_no'].'"
                      },
                      "keyword2": {
                        "value": "已支付"
                      },
                      "keyword3": {
                        "value": "￥'.number_format($order['pay_fee']/100, 2).'"
                      },
                      "keyword4": {
                        "value": "'.date('Y-m-d H:i').'"
                      },
                      "keyword5": {
                        "value": "'.substr($plist, 0, -1).'"
                      }
                  }';

            $message = new Wxmessage($formId, $user['openid'], '8gWjXbRXJ1U7DfeaqVxzS25_MYCh8VLoljCl8wTD4i4', $data, $order['order_no'], 1);
            $message->smallWXmessage();
    }

    

    /**
     * 订单列表
     * @return [type] [description]
     */
    public function orderList()
    {
        $userId = input('param.user_id',0);
        $status = input('param.status',0);
        $pageno   = input('get.pageno', 0);
        $pagesize = input('get.pagesize', 10);

        if(empty($userId)){
            $this->ajaxReturn([], '用户为空', 201);
        }
        
        $where['user_id'] = $userId;
        $where['status'] = ['<>',-9];
        if($status){
            $where['status'] = $status;
        }

        $count = db('order')->where($where)->count();
        $Page = new \VuePage($count,10);
        $list = db('order')->where($where)->order('order_id desc')->limit($Page->getStart(),$Page->getEnd())->select();
        $Page->setData($list);
        $return = $Page->indexjson();
        
        $return['info'] = 'ok';
        $return['status'] = 200;
        $this->_ajaxReturn($return);
    }





    /**
     * 订单删除
     * @return [type] [description]
     */
    public function orderdel()
    {
        $orderId = input('param.order_id', 0);
        if(empty($orderId)){
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $order = db('order')->where('order_id', $orderId)->field('order_id,status')->find();
        if(empty($order)){
            $this->ajaxReturn(null, '订单无效', 202);
        }

        $res = db('order')->where('order_id', $orderId)->update(['status'=>-9]);
        if ($res) {
            $this->ajaxReturn($res, '删除成功', 200);
        }else{
            $this->ajaxReturn(null, '删除失败', 204);
        }
    }

 
    

}

